package com.southminority.ethnic.service.member.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.southminority.ethnic.common.exception.BusinessException;
import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.mapper.member.MemberMapper;
import com.southminority.ethnic.pojo.Member;
import com.southminority.ethnic.service.member.MemberService;
import com.southminority.ethnic.controller.member.vo.MemberVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 团队成员服务实现类.
 * <p>
 * 实现了 {@link MemberService} 接口，负责处理所有与团队成员相关的业务逻辑。
 * 包括数据查询、转换、增删改查等操作。
 *
 * @author SouthMinority
 */
@Slf4j
@Service
public class MemberServiceImpl implements MemberService {

    private final MemberMapper memberMapper;
    private final ObjectMapper objectMapper;

    public MemberServiceImpl(MemberMapper memberMapper, ObjectMapper objectMapper) {
        this.memberMapper = memberMapper;
        this.objectMapper = objectMapper;
    }

    // =================================================================================
    // ==                             前端展示相关方法 (Public API)                     ==
    // =================================================================================

    @Override
    public List<MemberVO> getAllMembers() {
        // 构建查询条件：状态为已启用(1)，并按排序值升序、创建时间降序排列
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .orderByAsc("sort_order")
               .orderByDesc("create_time");

        List<Member> memberList = memberMapper.selectList(wrapper);
        return memberList.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<MemberVO> getAllMembersByOrganization(Long organizationId) {
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        if (organizationId != null) {
            wrapper.eq("organization_id", organizationId);
        }
        wrapper.orderByAsc("sort_order").orderByDesc("create_time");
        List<Member> list = memberMapper.selectList(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public MemberVO getMemberDetail(Long id) {
        // 校验ID
        if (id == null) {
            throw new BusinessException("成员ID不能为空");
        }

        // 查询数据库
        Member member = memberMapper.selectById(id);
        // 校验成员是否存在以及是否为已启用状态
        if (member == null || member.getStatus() != 1) {
            throw new BusinessException("团队成员不存在或已被禁用");
        }

        return convertToVO(member);
    }

    @Override
    public List<String> getDepartments() {
        // 查询所有不重复的部门名称，用于前端筛选菜单
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT department")
               .eq("status", 1) // 只统计已启用的成员
               .isNotNull("department")
               .orderByAsc("department");

        List<Member> list = memberMapper.selectList(wrapper);
        return list.stream()
                .map(Member::getDepartment)
                .filter(StringUtils::hasText) // 过滤空字符串
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getTitles() {
        // 查询所有不重复的职称名称，用于前端筛选菜单
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT title")
               .eq("status", 1) // 只统计已启用的成员
               .isNotNull("title")
               .orderByAsc("title");

        List<Member> list = memberMapper.selectList(wrapper);
        return list.stream()
                .map(Member::getTitle)
                .filter(StringUtils::hasText)
                .collect(Collectors.toList());
    }


    // =================================================================================
    // ==                             后台管理相关方法 (Admin API)                      ==
    // =================================================================================

    @Override
    public PageResult<MemberVO> getMemberPageForAdmin(Integer page, Integer size, String name,
                                                      String department, String title, Integer status) {
        return getMemberPageForAdmin(page, size, name, department, title, status, null);
    }

    @Override
    public PageResult<MemberVO> getMemberPageForAdmin(Integer page, Integer size, String name,
                                                      String department, String title, Integer status, Long organizationId) {
        Page<Member> pageObj = new Page<>(page, size);
        QueryWrapper<Member> wrapper = new QueryWrapper<>();

        if (StringUtils.hasText(name)) wrapper.like("name", name);
        if (StringUtils.hasText(department)) wrapper.eq("department", department);
        if (StringUtils.hasText(title)) wrapper.eq("title", title);
        if (organizationId != null) wrapper.eq("organization_id", organizationId);
        if (status != null) wrapper.eq("status", status); else wrapper.ne("status", -1);

        wrapper.orderByAsc("sort_order").orderByDesc("create_time");

        IPage<Member> pageResult = memberMapper.selectPage(pageObj, wrapper);
        List<MemberVO> voList = pageResult.getRecords().stream().map(this::convertToVO).collect(Collectors.toList());
        return PageResult.<MemberVO>builder()
                .current(pageResult.getCurrent())
                .size(pageResult.getSize())
                .total(pageResult.getTotal())
                .pages(pageResult.getPages())
                .records(voList)
                .build();
    }

    @Override
    @Transactional
    public MemberVO createMember(Member member) {
        if (member == null) {
            throw new BusinessException("成员信息不能为空");
        }

        // 设置创建时的默认值
        if (member.getStatus() == null) member.setStatus(1); // 默认为启用
        if (member.getSortOrder() == null) member.setSortOrder(0);

        // 插入数据库
        int result = memberMapper.insert(member);
        if (result <= 0) {
            throw new BusinessException("创建团队成员失败");
        }

        return convertToVO(member);
    }

    @Override
    @Transactional
    public MemberVO updateMember(Long id, Member member) {
        if (id == null || member == null) {
            throw new BusinessException("参数不能为空");
        }

        // 校验成员是否存在
        Member existingMember = memberMapper.selectById(id);
        if (existingMember == null) {
            throw new BusinessException("团队成员不存在");
        }

        member.setId(id); // 保证ID正确
        member.setUpdateTime(LocalDateTime.now());

        // 执行更新
        int result = memberMapper.updateById(member);
        if (result <= 0) {
            throw new BusinessException("更新团队成员失败");
        }

        // 返回更新后的最新数据
        return convertToVO(memberMapper.selectById(id));
    }

    @Override
    @Transactional
    public boolean deleteMember(Long id) {
        if (id == null) {
            throw new BusinessException("成员ID不能为空");
        }

        Member member = memberMapper.selectById(id);
        if (member == null) {
            // 如果成员已不存在，也认为操作成功，避免重复删除报错
            return true;
        }

        // 逻辑删除：将状态设置为-1
        member.setStatus(-1);
        member.setUpdateTime(LocalDateTime.now());

        int result = memberMapper.updateById(member);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean batchDeleteMembers(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("成员ID列表不能为空");
        }

        // 批量查询存在的成员
        List<Member> memberList = memberMapper.selectBatchIds(ids);
        if (memberList.isEmpty()) {
            return true;
        }

        LocalDateTime now = LocalDateTime.now();
        for (Member member : memberList) {
            member.setStatus(-1);
            member.setUpdateTime(now);
            memberMapper.updateById(member);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean updateMemberStatus(Long id, Integer status) {
        if (id == null || status == null) {
            throw new BusinessException("参数不能为空");
        }
        // 状态值合法性校验
        if (status < -1 || status > 1) {
            throw new BusinessException("无效的状态值");
        }

        Member member = memberMapper.selectById(id);
        if (member == null) {
            throw new BusinessException("团队成员不存在");
        }

        member.setStatus(status);
        member.setUpdateTime(LocalDateTime.now());

        int result = memberMapper.updateById(member);
        return result > 0;
    }

    @Override
    public MemberVO getMemberDetailForAdmin(Long id) {
        if (id == null) {
            throw new BusinessException("成员ID不能为空");
        }
        Member member = memberMapper.selectById(id);
        if (member == null) {
            throw new BusinessException("团队成员不存在");
        }
        // 管理端接口不过滤status
        return convertToVO(member);
    }


    // =================================================================================
    // ==                             私有辅助方法 (Private Helpers)                      ==
    // =================================================================================

    /**
     * 将 Member POJO 转换为 MemberVO DTO.
     * <p>
     * 此方法负责处理复杂数据类型的转换，例如将数据库中存储的JSON字符串
     * 转换为Java的List<Map>，以便前端可以直接使用。
     *
     * @param member 数据库实体对象
     * @return 用于前端展示的视图对象
     */
    private MemberVO convertToVO(Member member) {
        if (member == null) {
            return null;
        }

        MemberVO vo = new MemberVO();
        BeanUtils.copyProperties(member, vo);

        // 安全地反序列化JSON字符串为List
        try {
            if (StringUtils.hasText(member.getSocialLinks())) {
                List<Map<String, String>> socialLinks = objectMapper.readValue(
                        member.getSocialLinks(),
                        new TypeReference<>() {}
                );
                vo.setSocialLinks(socialLinks);
            } else {
                // 如果JSON为空，则返回空列表，确保前端不会收到null
                vo.setSocialLinks(Collections.emptyList());
            }
        } catch (Exception e) {
            // 如果解析出错，记录错误日志并返回空列表
            log.error("解析团队成员(ID:{})的社交链接JSON失败: {}", member.getId(), e.getMessage());
            vo.setSocialLinks(Collections.emptyList());
        }

        return vo;
    }
} 
